<template>
    <div ref="warpRef" class="grid-table-cell" :class="{
        head: isHead
    }">
        <slot></slot>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, inject, onBeforeUnmount } from "vue"
import { TABLE_PROVIDE_KEY } from "./index"
const props = defineProps({
    isHead: {
        type: Boolean,
        default: false
    },
    width: {
        type: [Number, String],
        default: undefined
    },
    colSpan: {
        type: [Number, String],
        default: undefined
    },
    rowSpan: {
        type: [Number, String],
        default: undefined
    }
})
const TABLE_CONFIG:any = inject(TABLE_PROVIDE_KEY)

const warpRef = ref()
const cellKey = Symbol()
if(props.isHead){
    TABLE_CONFIG.value.setColumn(cellKey, {
        width: parseInt(props?.width ?? '0')
    })
}

onMounted(() => {
    if(props.isHead) setResizeWidth()
})

function setResizeWidth(){
    const callback = () => {
        TABLE_CONFIG.value.setColumn(cellKey, {
            width: warpRef.value.offsetWidth
        })
    }
    const rb = new ResizeObserver(callback)
    rb.observe(warpRef.value)
    onBeforeUnmount(() => {
        rb.unobserve(warpRef.value)
        rb.disconnect()
        TABLE_CONFIG.value.delColumn(cellKey)
    })
}
</script>

<style lang="less" scoped>
@border-color: #999;
.grid-table-cell{
    display: inline-flex;
    padding: 1px;
    min-height: 1em;
    &.head{
        font-weight: bold;
    }
}

.border{
    .grid-table-cell{
        border-bottom: 1px solid @border-color;
        border-right:  1px solid @border-color;
    }
    .grid-table-row{
        &:first-child>.grid-table-cell{
            border-top: 1px solid @border-color;
        }
        .grid-table-cell:first-child{
            border-left: 1px solid @border-color;
        }
    }
}
</style>